<script setup lang="ts">
import { h, onMounted, reactive, ref } from 'vue';

import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import {
  deleteChargeStandardApi,
  getChargeStandardApi,
  getChargeStandardIsUseByOrgApi,
  getChargeStandardUpdateApi,
  getSubCompanyApi,
} from '#/api';

import AddDrawer from './components/addDrawer.vue';
import CopyDrawer from './components/copyDrawer.vue';
import EditDrawer from './components/editDrawer.vue';
import { useRoute } from 'vue-router';
import { getAccountButtonAuth } from '#/api/core/auth';

const authInfo = ref({});
const router = useRoute();
const getAuth = () => {
  const query = {
    pageId: router.meta.id,
    userId: localStorage.getItem('userId'),
  };
  getAccountButtonAuth(query).then((res: any) => {
    // console.log(res)
    authInfo.value = res.data.data;
  });
  // console.log(router);
};
getAuth();
interface TreeNode {
  value: string;
  id: string;
  level: string;
  label: string;
  children?: TreeNode[];
}

const formState = reactive({
  regionID: undefined,
  year: undefined,
  menuName: undefined,
  keyword: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const companyOptions = ref<TreeNode[]>([]);
const isDrwaer = ref(false);
const isEditDrawer = ref(false);
const editData = ref({});
const isCopyDrawer = ref(false);
const copyData = ref({});
const yearOptions = ref([]);
const loading = ref(false);
const formRef = ref(null);
const isViewMode = ref(false);
const columns = [
  // {
  //   title: '序号',
  //   dataIndex: 'index',
  //   key: 'index',
  //   align: 'center',
  //   width: 80,
  //   ellipsis: true,
  // },
  {
    title: '子公司',
    dataIndex: 'comNameLevel5',
    key: 'comNameLevel5',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '标准名称',
    dataIndex: 'jfbzName',
    key: 'jfbzName',
    align: 'center',
    width: 150,
    ellipsis: true,
  },
  {
    title: '开始使用日期',
    dataIndex: 'beginUseDate',
    key: 'beginUseDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '结束使用日期',
    dataIndex: 'endUseDate',
    key: 'endUseDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '供暖开始日期',
    dataIndex: 'heatingStartDate',
    key: 'heatingStartDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '供暖结束日期',
    dataIndex: 'heatingEndDate',
    key: 'heatingEndDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '供热天数',
    dataIndex: 'heatingDays',
    key: 'heatingDays',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '停供申请开始日期',
    dataIndex: 'suspensionStartDate',
    key: 'suspensionStartDate',
    align: 'center',
    width: 150,
    ellipsis: true,
  },
  {
    title: '停供申请结束日期',
    dataIndex: 'suspensionEndDate',
    key: 'suspensionEndDates',
    align: 'center',
    width: 150,
    ellipsis: true,
  },
  {
    title: '停供系数',
    dataIndex: 'suspensionRate',
    key: 'suspensionRate',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '居民面积单价',
    dataIndex: 'jmAreaPrice',
    key: 'jmAreaPrices',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '非居民面积单价',
    dataIndex: 'fjmAreaPrice',
    key: 'fjmAreaPrice',
    align: 'center',
    width: 130,
    ellipsis: true,
  },
  {
    title: '办公面积单价',
    dataIndex: 'bgAreaPrice',
    key: 'bgAreaPrice',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '经营面积单价',
    dataIndex: 'jyAreaPrice',
    key: 'jyAreaPrice',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '开始制冷时间',
    dataIndex: 'coolinStartDate',
    key: 'coolinStartDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '结束制冷时间',
    dataIndex: 'coolingEndDate',
    key: 'coolinEndDate',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '制冷天数',
    dataIndex: 'coolingDays',
    key: 'coolinDays',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '制冷居民单价',
    dataIndex: 'jmCoolingPrice',
    key: 'jmCoolingPrice',
    align: 'center',
    width: 130,
    ellipsis: true,
  },
  {
    title: '制冷非居民单价',
    dataIndex: 'fjmCoolingPrice',
    key: 'fjmCoolingPrice',
    align: 'center',
    width: 130,
    ellipsis: true,
  },
  {
    title: '制冷办公单价',
    dataIndex: 'bgCoolingPrice',
    key: 'bgCoolingPrice',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '制冷经营单价',
    dataIndex: 'jyCoolingPrice',
    key: 'jyCoolingPrice',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '滞纳金收取范围',
    dataIndex: 'lateFeeRange',
    key: 'lateFeeRange',
    align: 'center',
    width: 140,
    ellipsis: true,
  },
  {
    title: '滞纳金计算方式',
    dataIndex: 'lateFeeMethod',
    key: 'lateFeeMethod',
    align: 'center',
    width: 140,
    ellipsis: true,
  },
  {
    title: '滞纳金额',
    dataIndex: 'lateFeeAmount',
    key: 'lateFeeAmount',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '滞纳金比例',
    dataIndex: 'lateFeeRate',
    key: 'lateFeeRate',
    align: 'center',
    width: 110,
    ellipsis: true,
  },
  {
    title: '滞纳金开始日期',
    dataIndex: 'lateFeeStartDate',
    key: 'lateFeeStartDate',
    align: 'center',
    width: 140,
    ellipsis: true,
  },
  {
    title: '滞纳金结束日期',
    dataIndex: 'lateFeeEndDate',
    key: 'lateFeeEndDate',
    align: 'center',
    width: 140,
    ellipsis: true,
  },
  {
    title: '优惠类型',
    dataIndex: 'discountType',
    key: 'discountType',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '优惠比例固定优惠',
    dataIndex: 'discountRate',
    key: 'discountRate',
    align: 'center',
    width: 150,
    ellipsis: true,
  },
  {
    title: '优惠金额固定优惠',
    dataIndex: 'discountAmount',
    key: 'discountAmount',
    align: 'center',
    width: 150,
    ellipsis: true,
  },
  {
    title: '精确单位',
    dataIndex: 'precisionUnit',
    key: 'precisionUnit',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '最大抹零金额',
    dataIndex: 'maxTrimZeroMoney',
    key: 'maxTrimZeroMoney',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '舍入计算规则',
    dataIndex: 'roundingCalculationRule',
    key: 'roundingCalculationRule',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '是否允许挂账',
    dataIndex: 'onAccount',
    key: 'onAccount',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '附件URL',
    dataIndex: 'attachmentURL',
    key: 'attachmentURL',
    align: 'center',
    width: 120,
    ellipsis: true,
  },
  {
    title: '审核状态',
    dataIndex: 'checkStatus',
    key: 'checkStatus',
    align: 'center',
    width: 100,
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'center',
    fixed: 'right',
    width: 300,
    ellipsis: true,
  },
];

const TableData = ref([]);
const editableData = reactive({});
const discountData = ref([]);
const editTitle = ref('编辑');
const formatTreeData = (data: any[]): TreeNode[] => {
  return data.map((item: any) => {
    const node: TreeNode = {
      value: item.levelID || item.id, // 确保 value 存在且唯一
      id: item.id,
      level: item.level,
      label: item.name,
      key: item.levelID || item.id, // key 和 value 保持一致
    };

    if (item.children && item.children.length > 0) {
      const children = formatTreeData(item.children);
      if (children.length > 0) {
        node.children = children;
      }
    }
    return node;
  });
};

const getSubCompany = () => {
  getSubCompanyApi().then((res: any) => {
    console.log(res);
    companyOptions.value = formatTreeData([{ ...res.data }]);
    console.log(companyOptions.value);
    // console.log();
  });
};

const generateYearOptions = () => {
  const currentYear = dayjs().year();
  const options = [];
  for (let i = 0; i < 5; i++) {
    const startYear = currentYear - i;
    const endYear = startYear + 1;
    options.push({
      value: `${startYear}`,
      label: `${startYear}-${endYear}`,
    });
  }
  yearOptions.value = options;
};

onMounted(() => {
  generateYearOptions();
  getTableData();
  getSubCompany();
});

const getTableData = async () => {
  loading.value = true;
  const query = {
    page: pagination.current,
    limit: pagination.pageSize,
    year: formState.year ?? '',
    // 数组以逗号分隔
    treeData: formState.regionID ? formState.regionID.join(',') : '',
    jfbzName: formState.jfbzName ?? '',
  };
  const res = await getChargeStandardApi(query.page, query.limit, query);
  if (res.data) {
    loading.value = false;
    TableData.value = res.data;
    pagination.total = res.data.total;
  }
};
const handleReset = () => {
  formRef.value?.resetFields();
  getTableData();
};
const handleView = async (record: any) => {
  editTitle.value = '查看';
  isViewMode.value = true;
  editData.value = record;
  isEditDrawer.value = true;
};

const handleEdit = async (record: any) => {
  editTitle.value = '编辑';
  isViewMode.value = false;
  const res = await getChargeStandardIsUseByOrgApi(record.jfbzID);
  editData.value = record;
  if (res === 0) {
    isEditDrawer.value = true;
  } else {
    message.warning('该计费规则已被使用，无法修改');
  }
};

const onDetel = async (e: any) => {
  // 执行接口检测是否使用
  const res = await getChargeStandardIsUseByOrgApi(e.jfbzID);
  if (res === 0) {
    const res = await deleteChargeStandardApi(e.jfbzID, e.regionID);
    if (res === '删除成功') {
      message.success('删除成功');
      getTableData();
    } else {
      message.error('删除失败');
    }
  }
};

const onCopy = async (e: any) => {
  if (e.discountType === '分时段优惠') {
    message.warning('分时段优惠暂不支持复制');
  } else {
    copyData.value = e;
    isCopyDrawer.value = true;
  }
};

const onDiscount = async (e: any) => {
  const res = await getChargeStandardUpdateApi(e.jfbzID);
  if (res) {
    discountData.value = res;
  }
};
</script>

<template>
  <div class="p-5">
    <a-card>
      <a-form layout="inline" :model="formState" ref="formRef">
        <a-form-item label="子公司" name="regionID" s>
          <a-tree-select
            v-model:value="formState.regionID"
            :tree-data="companyOptions"
            tree-checkable
            allow-clear
            style="width: 300px"
            placeholder="请选择子公司"
            :max-tag-count="2"
          />
        </a-form-item>
        <a-form-item label="年度" name="year">
          <a-select
            v-model:value="formState.year"
            :options="yearOptions"
            style="width: 200px"
            placeholder="请选择年度"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="标准名称" name="jfbzName">
          <a-input
            v-model:value="formState.jfbzName"
            placeholder="请输入标准名称"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="getTableData">搜索</a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="handleReset">重置</a-button>
        </a-form-item>
        <a-form-item>
          <a-button
            type="primary"
            :icon="h(PlusOutlined)"
            @click="isDrwaer = true"
            v-if="authInfo.adds==1"
          >
            新增
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <a-card class="mt-3">
      <div class="mb-3 mt-3">
        <a-table
          :columns="columns"
          :data-source="TableData"
          :pagination="false"
          :scroll="{ x: 3000, y: 300 }"
          :loading="loading"
        >
          <template #bodyCell="{ column, record }">
            <div v-if="column.key === 'action'">
              <a-button type="link" @click="handleEdit(record)" v-if="authInfo.updates==1">修改</a-button>
              <a-button type="link" @click="handleView(record)">查看</a-button>
              <a-popconfirm
                title="确定要删除这条计费规则吗？"
                placement="bottom"
                ok-text="确定"
                cancel-text="取消"
                @confirm="onDetel(record)"
              >
                <a-button type="link" v-if="authInfo.deletes==1">删除</a-button>
              </a-popconfirm>
              <a-button type="link" @click="onCopy(record)" v-if="authInfo.adds==1">复用</a-button>
            </div>
            <div v-if="column.key === 'checkStatus'">
              <a-tag v-if="record.checkStatus === '待审核'" color="yellow">
                待审核
              </a-tag>
              <a-tag v-if="record.checkStatus === '审核通过'" color="green">
                审核通过
              </a-tag>
            </div>
            <div v-if="column.key === 'discountType'">
              <a-popover
                title="分时段优惠"
                v-if="record.discountType === '分时段优惠'"
                placement="bottom"
                trigger="click"
              >
                <template #content>
                  <div class="text-center">
                    <a-spin v-if="discountData.length === 0" />
                    <div v-else>
                      <a-descriptions
                        size="small"
                        bordered
                        v-for="item in discountData"
                        :key="item.jfbzID"
                        class="mt-3"
                      >
                        <a-descriptions-item label="优惠金额" :span="1">
                          {{ item.discountAmount }}
                        </a-descriptions-item>
                        <a-descriptions-item label="优惠比例" :span="2">
                          {{ item.discountRate }}
                        </a-descriptions-item>
                        <a-descriptions-item label="开始时间">
                          {{ item.discountStartDate }}
                        </a-descriptions-item>
                        <a-descriptions-item label="结束时间">
                          {{ item.discountEndDate }}
                        </a-descriptions-item>
                      </a-descriptions>
                    </div>
                  </div>
                </template>
                <a-tag
                  color="green"
                  class="cursor-pointer"
                  @click="onDiscount(record)"
                >
                  分时段优惠
                </a-tag>
              </a-popover>

              <a-tag v-else color="blue">{{ record.discountType }}</a-tag>
            </div>
          </template>
        </a-table>
      </div>
    </a-card>
    <AddDrawer
      :open="isDrwaer"
      @handle-close="isDrwaer = false"
      @handle-save="getTableData"
      title="新增计费规则"
    />
    <EditDrawer
      :open="isEditDrawer"
      :data="editData"
      :disabled="isViewMode"
      :title="editTitle"
      @handle-close="
        () => {
          isEditDrawer = false;
          isViewMode = false;
        }
      "
      @handle-save="getTableData"
    />
    <CopyDrawer
      :open="isCopyDrawer"
      :data="copyData"
      @handle-close="isCopyDrawer = false"
      @handle-save="getTableData"
    />
  </div>
</template>

<style scoped></style>
